package Bill.app.serveur;


import java.awt.Dimension;
import java.awt.Font;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketImpl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import Bill.app.serveur.bean.dao.implement.MainDaoImplement;
import Bill.util.Configuration;
 

public class SERVEUR extends JFrame
    implements ActionListener, WindowListener
{
	public   static MainDaoImplement em;

    private static int Config_portServeur=60000;
	public SERVEUR()
        throws Throwable
    {
       
        bloquerClient = new JMenuItem("boquer un client");
        supprimerClient = new JMenuItem("supprimer un cliet");
        activerClient = new JMenuItem("activer un client");
        quitter = new JMenuItem("arreter le serveur");
        
        vider = new JButton("vider l'ECRAN");
        ECRAN.setFont(new Font("Verdana", 1, 13));
        JScrollPane scroller = new JScrollPane(ECRAN);
        scroller.setVerticalScrollBarPolicy(22);
        scroller.setHorizontalScrollBarPolicy(30);
        scroller.setPreferredSize(new Dimension(300, 150));
        scroller.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("INFO SUR LE SERVEUR "), BorderFactory.createEmptyBorder(5, 5, 5, 5)), scroller.getBorder()));
        JMenu fichier = new JMenu("Fichier");
        JMenu Action = new JMenu("Action");
        JMenu creer = new JMenu("Creer ...");
        fichier.add(quitter);
        fichier.addSeparator();
        
        quitter.addActionListener(this);
        Action.add(creer);
         
        Action.addSeparator();
        Action.add(bloquerClient);
        bloquerClient.addActionListener(this);
        Action.addSeparator();
        Action.add(supprimerClient);
        supprimerClient.addActionListener(this);
        Action.addSeparator();
        Action.add(activerClient);
        activerClient.addActionListener(this);
        JMenuBar bar = new JMenuBar();
        bar.add(fichier);
        bar.add(Action);
        setJMenuBar(bar);
        vider.setToolTipText("vider l'ecran");
        vider.setMnemonic('V');
        vider.addActionListener(this);
        add("Center", scroller);
        add("South", vider);
        ECRAN.setVisible(true);
           addWindowListener(this);
        setSize(600, 600);
        setVisible(true);
        new ServeurGroup(ECRAN);
        try{
        ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("application.xml");
       em=ctx.getBean( MainDaoImplement.class);
        }catch(Exception e){
        	System.err.println("unable to start the server because  entity manager is not instanciated \n cause by "+e.getMessage());
        	System.exit(-1);
        }

    }
    
     
    public static void main(String args[])
        throws Throwable
    {
        SERVEUR hh = new SERVEUR();
        Configuration.loadConfiguration();
        lesocket = new ServerSocket(Configuration.Config_portServeur);
        ECRAN.addItem("serveur lanc\351 en attente de connexion ...");
        do
        {
            try
            {
                paquet = lesocket.accept();
            }
            catch(SocketException e)
            {
                ECRAN.addItem((new StringBuilder("erreur:  ")).append(e).toString());
            }
            if(paquet==null)continue;
            String text = (new BufferedReader(new InputStreamReader(paquet.getInputStream()))).readLine();
            char c = text.charAt(0);
            ECRAN.addItem((new StringBuilder("code operation: ")).append(c).toString());
            switch(c)
            {
            case Protocole.Auth: // '1'
                ECRAN.addItem("    connexion d'un client");
                new ThreadConnexion(paquet, text);
                break;

            case Protocole.Ami: // '2'
                new ThreadRaptrieAmi(paquet, text, LesConnecter);
                break;

            case Protocole.Ajout: // '3'
                ECRAN.addItem("   Ajout de contact ");
                new ThreadAjout(paquet, text);
                break;

            case Protocole.Chat: // '4'
                new NThreadChatSERV(paquet, LesConnecter, tableChat, text);
                ECRAN.addItem("  acc\350s   discussion");
                break;

            case Protocole.NouveauCompte: // '5'
                new ThreadNouveauCompte(paquet, text);
                ECRAN.addItem("   nouveau client");
                break;

            case Protocole.ChangeId: // '6'
                ECRAN.addItem("changement d'identifiant d'un client");
                new IDChange(paquet, text);
                break;

            case Protocole.Deconnexion: // '7'
                new ThreadDeconnexion(paquet, LesConnecter, listeLogin, text);
                nombreconnecte--;
                ECRAN.addItem("un client vient de se deconnecter");
                break;

            case Protocole.Connexion: // '8'
                ECRAN.addItem((new StringBuilder("un client vient de se connecter   son IP:")).append(paquet.getInetAddress()).append("      son port ").append(paquet.getPort()).toString());
                new ServMessagerie(paquet, LesConnecter, listeLogin, text);
                nombreconnecte++;
                ECRAN.addItem("un client vient de se connecter");
                break;

            default:
                ECRAN.addItem(" collision detect\351e !!:code corrompu!!");
                String mes = "collision detect\351e !!:code corrompu!!";
                (new PrintWriter(new BufferedWriter(new OutputStreamWriter(paquet.getOutputStream())))).println(mes);
                paquet.close();
                break;
            }
            hh.setTitle((new StringBuilder("BZHSERVEUR 1.0             nombre de connect\351s :")).append(nombreconnecte).toString());
        } while(true);
    }

    public void actionPerformed(ActionEvent arg0)
    {
        Object obj = arg0.getSource();
        if(obj == vider)
            ECRAN.removeAll();
        else
       
        if(obj == activerClient || obj == bloquerClient || obj == supprimerClient)
            new ActionSurClient();
         
    }

    public void windowActivated(WindowEvent windowevent)
    {
    }

    public void windowClosed(WindowEvent arg0)
    {
        int n = LesConnecter.size();
        for(int i = 0; i < n; i++)
            ((PrintWriter)LesConnecter.get(listeLogin.get(i))).println("END");

        System.exit(0);
    }

    public void windowClosing(WindowEvent arg0)
    {
        int n = LesConnecter.size();
        for(int i = 0; i < n; i++)
            ((PrintWriter)LesConnecter.get(listeLogin.get(i))).println("END");

        listeLogin.removeAllElements();
        try
        {
            lesocket.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        System.exit(0);
    }

    public void windowDeactivated(WindowEvent windowevent)
    {
    }

    public void windowDeiconified(WindowEvent windowevent)
    {
    }

    public void windowIconified(WindowEvent windowevent)
    {
    }

    public void windowOpened(WindowEvent windowevent)
    {
    }

    private static final long serialVersionUID = 1L;
    static List ECRAN = new List();
   
    public static long nombreconnecte = 0L;
     
    JMenuItem bloquerClient;
    JMenuItem supprimerClient;
    JMenuItem activerClient;
    JMenuItem quitter;
    
    static java.util.Hashtable LesConnecter = new java.util.Hashtable();
    static java.util.Vector listeLogin = new java.util.Vector();
    static java.util.Hashtable tableChat = new java.util.Hashtable();
    static ServerSocket lesocket = null;
    static Socket paquet = null;
    JButton vider;
	/**
	 * @return the em
	 */
	public synchronized static MainDaoImplement getEm() {
		return em;
	}


	 
	

}
